import { IResAndReqFieldsMap, IResAndReqFields, IField } from "../../interface/type"
import utilTool from "../../util/tool"
import util from "../common/util"

let childrenRefObj: Set<string>

function formatFieldToInterface(fields: IField[], name: string): string[] {
  const arr: string[] = []
  let children: string[] = []

  const fieldNameMap: Set<string> = new Set()
  fields.forEach(it => {
    fieldNameMap.add(it.name)
  })

  if (name === 'IPageRequest' || name === 'PageRequest' || fields?.length === 0) {
    return arr
  }

  if (fieldNameMap.has('pageRequest')) {
    arr.push(`export interface I${name} extends PageParam {`)
  } else if (fieldNameMap.has('current') && fieldNameMap.has('pages') && fieldNameMap.has('size')) {
    arr.push(`export interface I${name} extends PageRequest {`)
  } else {
    arr.push(`export interface I${name} {`)
  }

  for (const field of fields) {
    console.log('----field.childrenRef>-------------', field.childrenRef, field.children, field.childrenRef && !childrenRefObj.has(field.childrenRef))
    if (field.children && field.children.length > 0 && field.childrenRef && !childrenRefObj.has(field.childrenRef)) {
      const childrenName: string = utilTool.firstUp(field.name)
      children = children.concat(formatFieldToInterface(field.children, childrenName))
      childrenRefObj.add(field.childrenRef)
    }
    if ( !(fieldNameMap.has('pageRequest') && field.name === 'pageRequest') &&
      !(fieldNameMap.has('current') && fieldNameMap.has('pages') && fieldNameMap.has('size') && utilTool.checkStrEqualKeyWord(field.name, ['current', 'pages', 'searchCount', 'size', 'total']))
      ) {
      arr.push(`${field.name}${field.isReq ? '' : '?'}: ${util.getType(field, name)}; ${field.description ? '// ' + field.description : ''}
    `)
    }
  }
  arr.push(`}
  `)
  return arr.concat(children)
}

function getDef(apiPramAndResMap: IResAndReqFieldsMap) {
  let strArr: string[] = []
  childrenRefObj = new Set()
  for (const key of Object.keys(apiPramAndResMap)) {
    const item: IResAndReqFields = apiPramAndResMap[key]
    strArr = strArr.concat(formatFieldToInterface(item.request, utilTool.firstUp(key) + 'Param'))
    strArr = strArr.concat(formatFieldToInterface(item.response, utilTool.firstUp(key) + 'Respon'))
  }
  return strArr.join('')
}

export function apiModelTemp(apiPramAndResMap: IResAndReqFieldsMap): string {
  return `import { PageRequest, PageParam } from '/@/api/common/common';
  ${getDef(apiPramAndResMap)}
  `
}
